package com.kika.obwiki.service.impl;

import com.kika.obwiki.entity.Doc;
import com.kika.obwiki.entity.Content;
import com.kika.obwiki.mapper.DocMapper;
import com.kika.obwiki.service.IDocService;
import com.kika.obwiki.service.IContentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kika.obwiki.utils.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kika.obwiki.utils.CopyUtil;
import com.kika.obwiki.resp.DocQueryResp;
import com.kika.obwiki.rep.DocQueryReq;
import com.kika.obwiki.rep.DocSaveReq;
import com.kika.obwiki.resp.PageResp;
import com.kika.obwiki.mapper.EbookMapper;
import com.kika.obwiki.utils.RedisUtil;
import com.kika.obwiki.utils.RequestContext;
import com.kika.obwiki.exception.BusinessException;
import com.kika.obwiki.exception.BusinessExceptionCode;
import com.kika.obwiki.websocket.WsServiceAsync;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import javax.annotation.Resource;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cr
 * @since 2025-06-22
 */
@Service
public class DocServiceImpl extends ServiceImpl<DocMapper, Doc> implements IDocService {

    @Autowired
    private SnowFlake snowFlake;

    @Autowired
    private IContentService contentService;

    @Autowired
    private EbookMapper ebookMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private DocMapper docMapper;

    @Autowired
    private WsServiceAsync wsServiceAsync;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public PageResp<DocQueryResp> listByname(DocQueryReq req) {

        QueryWrapper<Doc> queryWrapper = new QueryWrapper<Doc>();
        // 第一个参数：该参数是一个布尔类型，只有该参数是true时，才将like条件拼接到sql中；本例中，如果name字段不为空，则拼接name字段的like查询条件；
        queryWrapper.like(StringUtils.isNotBlank(req.getName()), "name", req.getName());
        // 创建分页对象
        Page<Doc> page = new Page<>(req.getPage(), req.getSize());
        page = this.baseMapper.selectPage(page, queryWrapper);

        List<DocQueryResp> resps = CopyUtil.copyList(page.getRecords(), DocQueryResp.class);
        // 创建返回对象
        PageResp<DocQueryResp> pageResp = new PageResp<>();
        pageResp.setList(resps);
        pageResp.setTotal(page.getTotal());
        return pageResp;
    }

    @Override
    public void save(DocSaveReq req) {
        Doc doc = CopyUtil.copy(req, Doc.class);
        Content content = CopyUtil.copy(req, Content.class);

        if (ObjectUtils.isEmpty(req.getId())) {
            // 新增文档
            long id = snowFlake.nextId();
            doc.setId(id);
            doc.setViewCount(0); // 默认查看点赞为0
            doc.setVoteCount(0);
            this.baseMapper.insert(doc);

            // 新增内容
            content.setId(id);
            contentService.save(content);
        } else {
            // 更新文档
            this.baseMapper.updateById(doc);
            boolean b = contentService.updateById(content); // 更新内容
            if (!b) { // 根据id更新失败,执行新增功能
                contentService.save(content);
            }
        }
    }

    @Override
    public void delete(Long id) {
        this.baseMapper.deleteById(id);
    }

    /**
     * 批量删除文档
     * 
     * @param ids 文档 id 列表
     */
    @Override
    public void delete(List<Long> ids) {
        if (ids != null && !ids.isEmpty()) {
            this.baseMapper.deleteBatchIds(ids);
        }
    }

    @Override
    public List<DocQueryResp> all() {
        return all(null);
    }

    @Override
    public List<DocQueryResp> all(Long ebookId) {
        // 电子书阅读数+1
        if (ebookId != null) {
            ebookMapper.increaseViewCount(ebookId);
        }
        QueryWrapper<Doc> queryWrapper = new QueryWrapper<>();
        if (ebookId != null) {
            queryWrapper.eq("ebook_id", ebookId);
        }
        queryWrapper.orderBy(true, true, "sort");
        List<Doc> docList = this.baseMapper.selectList(queryWrapper);
        return CopyUtil.copyList(docList, DocQueryResp.class);
    }

    /**
     * 文档点赞（防重复）
     * 
     * @param id 文档ID
     */
    @Override
    public void vote(Long id) {
        // key为 DOC_VOTE_文档id_远程ip
        String key = "DOC_VOTE_" + id + "_" + RequestContext.getRemoteAddr();
        if (redisUtil.validateRepeat(key, 3600 * 24)) {
            this.baseMapper.increaseVoteCount(id);
        } else {
            throw new BusinessException(BusinessExceptionCode.VOTE_REPEAT);
        }
        // 查询点赞文档信息
        Doc doc = this.baseMapper.selectById(id);
        // 发送RocketMQ消息
        rocketMQTemplate.convertAndSend("VOTE_TOPIC", "【" + doc.getName() + "】被点赞！");
    }

    /**
     * 定时批量更新电子书统计信息（文档数、阅读数、点赞数等）
     * 调用DocMapper的SQL实现，供定时任务调用
     *
     * @author cr
     */
    @Override
    public void updateEbookInfo() {
        docMapper.updateEbookInfo();
    }
}
